import { OneModal } from '@/components/one-ui';
import { ContractManageAPI } from '../common/type';
import { IOneModalRef } from '@/pages/type';
import { Ref, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { UpdateTableCommon } from './UpdateTableCommon';
import { ConractControllerContext, IContractsActionEnum } from '../common';
import { openContractSubjectManage } from '../services';
import { openCounterpartColumns } from '../mconfig';
import { Button, Space, message } from 'antd';
import { getCompanyID, getKeyRouter, getPosIDs, getUserDepID, getUserID, onCloseModalCommon } from '@/utils';
import { OpenCounterpartModalForm } from './OpenCounterpartModalFrom';

export const OpenCounterpartModal: React.FC<ContractManageAPI.IOpenCounterpartModal> = ({ onClose, openModal }) => {
  /** 弹框高度样式 */
  const modalBodyStyle: React.CSSProperties = {
    height: document.body.clientHeight * 0.55,
    padding: 0,
  };

  /**弹框的ref*/
  const counterModalRef: Ref<IOneModalRef> = useRef(null);

  /** 获取上下文 */
  const { curRes, counterpartRows, styleFixCls, contarctJsonList, contractDispatch, contractDetailInfo } = useContext(ConractControllerContext);

  /** 获取列表 */
  const { data, params, loading, pagination, searchList, getManageData, refreshManage } = openContractSubjectManage(curRes, false);

  /** 暂时保存选中的值 */
  const [briefCounterList, setBriefCounterList] = useState<Record<string, any>[]>([]);

  /** 相对方 tab */
  const [openCounterFormModal, setOpenCounterFormModal] = useState<boolean>(false);

  /** 初始化选中 */
  useEffect(() => {
    if (openModal && counterpartRows?.length > 0) {
      setBriefCounterList(counterpartRows);
    }
  }, [openModal, counterpartRows]);

  /** 搜索 */
  const onSearch = (payload: Record<string, any>) => {
    getManageData({ ...payload });
  };

  /** 重置 */
  const onReset = (payload: Record<string, any>) => {
    getManageData({ ...payload });
  };

  /** 点击选中 */
  const onSelectTable = (selectInfo: any) => {
    setBriefCounterList(selectInfo);
    // contractDispatch({
    //   type: IContractsActionEnum.SELECT_COUNTERPARTROWS,
    //   payload: selectInfo,
    // });
  };

  /** 分页change 方法 */
  const onPageChange = (current: number, pageSize: number) => {
    getManageData({ ...params, current, pageSize });
  };

  /** 相对方数据处理 */
  const dataRowsMemo = useMemo(() => {
    let dataRows: Record<string, any>[] = [];
    data?.rows?.forEach((item: any) => {
      const itemObj: Record<string, any> = {
        ...item,
        oppositeID: item?.id,
      };
      dataRows?.push(itemObj);
    });
    return dataRows;
  }, [data?.rows]);

  const onSaveReset = () => {
    if (briefCounterList && briefCounterList?.length > 0) {
      const brieList: Record<string, any>[] = [];
      briefCounterList?.forEach((item: any) => {
        const itemInfo = dataRowsMemo?.find((itemFind: any) => itemFind?.oppositeID == item?.oppositeID);
        brieList.push({
          ...item,
          oppositeName: itemInfo ? itemInfo?.fullName : item?.oppositeName,
          oppositeID: itemInfo ? itemInfo?.id : item?.id,
          phoneMobile: itemInfo ? itemInfo?.contactMobile : item?.phoneMobile,
          contractID: null,
          oppositeType: 0,
          createrID: getUserID(),
          createPositionID: getPosIDs(),
          createDepartmentID: getUserDepID(),
          createCompanyID: getCompanyID(),
          versionNum: 0,
          modifyFlag: 0,
          key: `id-${getKeyRouter()}`,
        });
      });

      contractDispatch({
        type: IContractsActionEnum.SELECT_COUNTERPARTROWS,
        payload: brieList,
      });

      let oppositeList: Record<string, any>[] = contractDetailInfo?.oppositeList?.length > 0 ? contractDetailInfo?.oppositeList : [];
      let addList: Record<string, any>[] = [];
      let delList: Record<string, any>[] = [];

      if (oppositeList && oppositeList?.length > 0) {
        brieList?.forEach((itemBrie: any) => {
          const addInfo = oppositeList?.find((itemInfo: any) => itemInfo?.oppositeID == itemBrie?.oppositeID);
          if (!(addInfo && addInfo?.oppositeID)) {
            delete itemBrie['id'];
            addList?.push({
              ...itemBrie,
              modifyFlag: '0',
            });
          }
        });
        oppositeList?.forEach((itemInfo: any) => {
          const delInfo = brieList?.find((itemBrie: any) => itemInfo?.oppositeID == itemBrie?.oppositeID);
          if (!(delInfo && delInfo?.oppositeID)) {
            delList?.push({
              ...itemInfo,
              modifyFlag: '2',
            });
          }
        });
      } else {
        addList = brieList;
      }

      contractDispatch({
        type: IContractsActionEnum.CONTRACT_JSONLIST,
        payload: {
          ...contarctJsonList,
          oppositeList: [...addList, ...delList],
        },
      });

      onCloseModalCommon(counterModalRef);
    } else {
      message.warning('请至少选择一位相对方！');
    }
  };

  // /** 保存 */
  // const onSave = () => {
  //   if (briefCounterList && briefCounterList?.length > 0) {
  //     const brieList: Record<string, any>[] = [];

  //     briefCounterList?.forEach((item: any) => {
  //       let itemInfo = dataRowsMemo?.find((itemFind: any) => itemFind?.oppositeID == item?.oppositeID);

  //       if(itemInfo) itemInfo = item;

  //       let itemObj: Record<string, any> = {
  //         contractID: null,
  //         oppositeID: itemInfo?.id,
  //         oppositeName: itemInfo?.fullName||itemInfo?.oppositeName,
  //         oppositeType: 0,
  //         legalName: itemInfo?.legalName,
  //         // empowerName: itemInfo?.empowerName,  //授权代表
  //         authName: itemInfo?.authName,
  //         contactName: itemInfo?.contactName,
  //         phoneMobile: itemInfo?.contactMobile||itemInfo?.phoneMobile,
  //         creditID: itemInfo?.creditID,
  //         bankName: itemInfo?.bankName,
  //         bankAccount: itemInfo?.bankAccount,
  //         registerPhone: itemInfo?.registerPhone,
  //         workAddress: itemInfo?.workAddress,
  //         createrID: getUserID(),
  //         createPositionID: getPosIDs(),
  //         createDepartmentID: getUserDepID(),
  //         createCompanyID: getCompanyID(),
  //         versionNum: 0,
  //         modifyFlag: 0,
  //         key: `id-${getKeyRouter()}`,
  //       };

  //       brieList?.push(itemObj);
  //     });

  //     contractDispatch({
  //       type: IContractsActionEnum.SELECT_COUNTERPARTROWS,
  //       payload: brieList,
  //     });

  //     let oppositeList: Record<string, any>[] = contractDetailInfo?.oppositeList?.length > 0 ? contractDetailInfo?.oppositeList : [];
  //     let addList: Record<string, any>[] = [];
  //     let delList: Record<string, any>[] = [];

  //     console.log('brieList',brieList)
  //     //如果原来有数据
  //     if (oppositeList && oppositeList?.length > 0) {
  //       brieList?.forEach((itemBrie: any) => {
  //         const addInfo = oppositeList?.find((itemInfo: any) => itemInfo?.oppositeID == itemBrie?.oppositeID);
  //         if (!(addInfo && addInfo?.oppositeID)) {
  //           delete itemBrie['id'];
  //           addList?.push({
  //             ...itemBrie,
  //             modifyFlag: '0',
  //           });
  //         }
  //       });
  //       oppositeList?.forEach((itemInfo: any) => {
  //         const delInfo = brieList?.find((itemBrie: any) => itemInfo?.oppositeID == itemBrie?.oppositeID);
  //         if (!(delInfo && delInfo?.oppositeID)) {
  //           delList?.push({
  //             ...itemInfo,
  //             modifyFlag: '2',
  //           });
  //         }
  //       });
  //     } else {
  //       addList = brieList;
  //     }

  //     contractDispatch({
  //       type: IContractsActionEnum.CONTRACT_JSONLIST,
  //       payload: {
  //         ...contarctJsonList,
  //         oppositeList: [...addList, ...delList],
  //       },
  //     });

  //     onCloseModalCommon(counterModalRef);
  //   } else {
  //     message.warning('请至少选择一位相对方！');
  //   }
  // };

  /** 弹框底部功能 */
  const footerBtns = () => {
    return (
      <Space>
        {curRes?.['/supplierInfoController/add'] && (
          <Button
            title="添加"
            type="default"
            // icon={<PlusOutlined />}
            onClick={() => {
              setOpenCounterFormModal(true);
            }}
          >
            添加
          </Button>
        )}

        <Button
          type="default"
          onClick={() => {
            onCloseModalCommon(counterModalRef);
          }}
        >
          取消
        </Button>
        <Button onClick={onSaveReset} type="primary">
          确认
        </Button>
      </Space>
    );
  };

  /** 表格配置 */
  const columns = useMemo(() => {
    if (openModal) {
      return openCounterpartColumns(
        () => {},
        () => {},
        false,
        () => {},
      );
    } else {
      return [];
    }
  }, [openModal]);

  return (
    <OneModal
      open={true}
      getContainer={false}
      ref={counterModalRef}
      title="选择相对方"
      onCancel={onClose}
      width={document.body.clientWidth * 0.65}
      bodyStyle={modalBodyStyle}
      footer={footerBtns()}
    >
      <UpdateTableCommon
        styleFixCls={styleFixCls}
        searchProps={{
          searchList,
          onReset,
          onSearch,
        }}
        selectTablePorps={{
          onSelectTable,
          selectRowObjList: briefCounterList,
          selectType: 'checkbox',
        }}
        tableProps={{
          rowKey: 'oppositeID',
          columns,
          loading,
          dataSource: dataRowsMemo,
          pagination,
          onPageChange,
        }}
      />

      {/* 添加相对方 */}
      {openCounterFormModal && (
        <OpenCounterpartModalForm
          onClose={() => {
            setOpenCounterFormModal(false);
          }}
          reloadManage={refreshManage}
        />
      )}
    </OneModal>
  );
};
